package com.woniuxy.dudugua.service.impl;

import com.woniuxy.dudugua.entity.*;
import com.woniuxy.dudugua.mapper.*;
import com.woniuxy.dudugua.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户业务层实现类
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ProductSkuMapper productSkuMapper;
    @Resource
    private ProductImagesMapper productImagesMapper;
    @Resource
    private CouponRuleMapper couponRuleMapper;
    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Resource
    private LogisticsMapper logisticsMapper;
    @Resource
    private AddressMapper addressMapper;
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private UserCouponsMapper userCouponsMapper;
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;
    /**
     * 根据手机号返回用户对象
     */
    public User loginByTel(String tel) {
        UserExample example = new UserExample();
        example.createCriteria().andTelEqualTo(tel);
        //因为手机号不允许重复，所以查出来只会有0个或者一个数据
        return userMapper.selectByExample(example)==null?null:userMapper.selectByExample(example).get(0);
    }

    /**
     * 根据用户id查询该用户的所有订单
     * @param userId
     * @return
     * @throws Exception
     */
    public List<Order> selectOrderById(int userId) throws Exception {
        //查询出所有订单信息
        OrderExample example1 = new OrderExample();
     /*   example1.createCriteria().andUserIdEqualTo(userId);
        List<Order> orders = orderMapper.selectByExample(example1);*/
        List<Order> orders = orderMapper.selectOderById(userId);
        List<OrderInfo> orderInfos = orderInfoMapper.selectByExample(null);
        if(orders!=null){
            //循环遍历，并且把商品sku表中的属性查出来，还有product表中的url查出来
            for(Order order:orders){
                //一个order里面有一个优惠券id，取出优惠券id并且不为0 的时候查出使用的优惠券
                if(order.getCouponId()!=0){
                    CouponRule couponRule = couponRuleMapper.selectByPrimaryKey(order.getCouponId());
                    order.setCouponRule(couponRule);
                }
                ArrayList<OrderInfo> list = new ArrayList<>();
                //一个order里面有多个orderInfo对象，取出一个order的order info，遍历orderinfo
                for(OrderInfo info:orderInfos){
                    if(info.getOrderId()==order.getId()){
                        //orderinfo对象中有productskuid，取出skuid，然后查询sku表，得到详细的信息
                        Integer productSkuId = info.getProductSkuId();
                        ProductSku sku = productSkuMapper.selectByPrimaryKey(productSkuId);
                        //取出sku对象中的productid，通过productId查询productImages表中的url并且状态为2的商品图片
                        Integer productId = sku.getProductId();
                        ProductImagesExample example = new ProductImagesExample();
                        example.createCriteria().andProductIdEqualTo(productId).andStatusEqualTo(2);
                        //因为商品首页图片只有一张，但是返回的是集合，所以直接取第0个元素的url
                        String url = productImagesMapper.selectByExample(example).get(0).getUrl();
                        //将这个商品图片设置到sku对象中
                        sku.setUrl(url);
                        info.setProductSku(sku);
                        list.add(info);
                    }
                }
                order.setOrderInfos(list);
            }
        }
        return orders;
    }

    /**
     * 传入一个orderid，修改order表种的status为5
     */
    public void cancelOrder(Integer orderId) throws Exception {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setStatus(5);
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 传入一个orderId，删除该order，并且删除订单详情表中的订单id
     */
    public void deleteOrder(Integer orderId) throws Exception {
        orderMapper.deleteByPrimaryKey(orderId);
        OrderInfoExample example = new OrderInfoExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        orderInfoMapper.deleteByExample(example);
    }

    /**
     * 传入一个user对象，注册
     * @param user
     * @throws Exception
     */
    public void register(User user) throws Exception {
        userMapper.insert(user);
    }

    /**
     * 传入一个user对象，更新user
     * @param user
     * @throws Exception
     */
    public void updateUser(User user) throws Exception {
        User u = (User) SecurityUtils.getSubject().getPrincipal();
        User user1 = userMapper.selectByPrimaryKey(u.getId());
        user1=user;
        userMapper.updateByPrimaryKeySelective(user1);
    }

    /**
     * 传入orderid，和userid，更新两个表中的数据
     * @param orderId
     * @param userId
     * @throws Exception
     */
    public void payOrder(int orderId, int userId) throws Exception {
        //分别查出两个数据
        Order order = orderMapper.selectByPrimaryKey(orderId);
        User user = userMapper.selectByPrimaryKey(userId);
        BigDecimal money1=user.getMoney();
        BigDecimal total = BigDecimal.valueOf(order.getTotal());
        user.setMoney(money1.subtract(total));
        order.setStatus(2);
        try {
            orderMapper.updateByPrimaryKeySelective(order);
            userMapper.updateByPrimaryKeySelective(user);
        }catch (Exception e){
            throw new Exception();
        }
    }

    /**
     * 传入一个orderid，修改order表种的status为4,待评价状态
     */
    public void commitOrder(int orderId) throws Exception {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setStatus(4);
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 传入一个快递单号，查询对应的公司代号
     * @param courierNumber
     * @return
     * @throws Exception
     */
    public String getCompanyCode(String courierNumber) throws Exception {
        LogisticsExample example = new LogisticsExample();
        example.createCriteria().andCourierNumberEqualTo(courierNumber);
        Logistics logistics = logisticsMapper.selectByExample(example).get(0);
        return logistics.getCompanyCode();
    }

    /**
     * 传入快递单号，查询orderid，然后通过orderid查询order表中的地址
     */
    public String getAddress(String courierNumber) throws Exception {
        String address = orderInfoMapper.selectAddress(courierNumber).get(0);
        return address;
    }

    /**
     * 传入userid，查询地址
     * @param userId
     * @return
     * @throws Exception
     */
    public User getUserAddress(Integer userId) throws Exception {
        AddressExample example = new AddressExample();
        example.createCriteria().andUserIdEqualTo(userId);
        User user = userMapper.selectUserAddressById(userId);
        return user;
    }

    /**
     * 传入用户id查询地址信息
     * @param userId
     * @return
     * @throws Exception
     */
    public List<Address> selectAddressByUserId(Integer userId) throws Exception {
        AddressExample example = new AddressExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<Address> addresses = addressMapper.selectByExample(example);
        return addresses;
    }

    /**
     * 传入用户id，查询用户信息
     * @param userId
     * @return
     * @throws Exception
     */
    public User selectInfo(Integer userId) throws Exception {

        return userMapper.selectByPrimaryKey(userId);
    }

    /**
     * 查看用户的所有评论
     * @param userId
     * @return
     * @throws Exception
     */
    public List<Comment> selectComment(Integer userId) throws Exception {
        CommentExample example = new CommentExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<Comment> comments = commentMapper.selectByExample(example);
        for(Comment comment:comments){
            String productName = productMapper.selectByPrimaryKey(comment.getProductId()).getProductName();
            ProductImagesExample example1 = new ProductImagesExample();
            example1.createCriteria().andProductIdEqualTo(comment.getProductId()).andStatusEqualTo(2);
            ProductImages productImage=productImagesMapper.selectByExample(example1).get(0);
            String url=productImage.getUrl();
            comment.setUrl(url);
            comment.setProductName(productName);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date time = comment.getTime();
            String format = sdf.format(time);
            comment.setCommentTime(format);
        }
        return comments;
    }

    /**
     * 传入一个orderinfoid，查询orderinfo
     * @param orderInfoId
     * @return
     * @throws Exception
     */
    public OrderInfo selectOrderInfo(Integer orderInfoId) throws Exception {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderInfoId);
        Integer orderId = orderInfo.getOrderId();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date time = orderMapper.selectByPrimaryKey(orderId).getAddTime();
        String format = sdf.format(time);
        orderInfo.setOrderTime(format);
        //根据orderinfo中的skuid，查询sku表中的productid，然后通过productid查询productimages表中的url，状态为2的
        Integer productSkuId = orderInfo.getProductSkuId();
        Integer productId = productSkuMapper.selectByPrimaryKey(productSkuId).getProductId();
        ProductImagesExample example = new ProductImagesExample();
        example.createCriteria().andProductIdEqualTo(productId).andStatusEqualTo(2);
        String url = productImagesMapper.selectByExample(example).get(0).getUrl();
        orderInfo.setProductUrl(url);
        return orderInfo;
    }

    /**
     * 传入skuid，查询productid
     * @param productSkuId
     * @return
     * @throws Exception
     */
    public int selectProductId(Integer productSkuId) throws Exception {
        return productSkuMapper.selectByPrimaryKey(productSkuId).getProductId();
    }

    /**
     * 新增评论
     * @param comment
     * @throws Exception
     */
    public void insertComment(Comment comment) throws Exception {
        //新增完成后，找到orderid，修改orderid中的status
        commentMapper.insert(comment);
        Integer orderInfoId = comment.getOrderInfoId();
        Integer orderId = orderInfoMapper.selectByPrimaryKey(orderInfoId).getOrderId();
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setStatus(6);
        orderMapper.updateByPrimaryKey(order);
    }

    @Override
    public int updateHead(User user) {
        int i = userMapper.updateByPrimaryKey(user);
        return i;
    }

    /**
     * 修改订单状态，返回余额，返回优惠券
     * @param orderId
     * @throws Exception
     */
    public void returnMoney(Integer orderId) throws Exception {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setStatus(5);
        orderMapper.updateByPrimaryKey(order);
        //取得userid和total
        Integer userId = order.getUserId();
        Double total = order.getTotal();
        User user = userMapper.selectByPrimaryKey(userId);
        user.setMoney(user.getMoney().add(BigDecimal.valueOf(total)));
        userMapper.updateByPrimaryKey(user);
        //返回优惠券
        if(order.getCouponId()!=0){
            //说明使用了优惠券，修改优惠券表中的status为1
            UserCoupons userCoupons = userCouponsMapper.selectByPrimaryKey(order.getCouponId());
            userCoupons.setStatus(1);
            userCouponsMapper.updateByPrimaryKey(userCoupons);
        }
    }

    /**
     * 传入一个orderid，增加一个returngoods数据
     * @param orderId
     * @throws Exception
     */
    public void wantReturn(Integer orderId) throws Exception {
        //先判断是不是已经申请过了，查询该orderid是否存在
        ReturnGoodsExample example = new ReturnGoodsExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        List<ReturnGoods> returnGoods = returnGoodsMapper.selectByExample(example);
        if(returnGoods.size()==0){
            //说明没有数据，新增一个
            ReturnGoods goods = new ReturnGoods();
            goods.setOrderId(orderId);
            goods.setStatus(1);
            returnGoodsMapper.insert(goods);
        }
    }

}
